<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item :label="t('su.invoice.no')" prop="no">
        <el-input
          v-model="queryParams.no"
          :placeholder="t('common.inputText') + t('su.invoice.no')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item :label="t('su.invoice.invoiceDate')" prop="invoiceDate">
        <el-date-picker
          v-model="queryParams.startDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="date"
          placeholder="Start Date"
          class="date-picker-item"
        />
        <el-date-picker
          v-model="queryParams.endDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="date"
          placeholder="End Date"
          class="date-picker-item"
        />
      </el-form-item>
      <el-form-item :label="t('su.invoice.kind')" prop="kind">
        <el-select
          v-model="queryParams.kind"
          :placeholder="t('common.inputText') + t('su.invoice.kind')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SU_INVOICE_KIND)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Customer Pay" prop="payStatus">
        <el-select
          v-model="queryParams.payStatus"
          placeholder="Select Pay Status"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in payStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="Saler" prop="no">
        <el-input
          v-model="queryParams.term"
          placeholder="Input Saler"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="Commission" prop="payStatus">
        <el-select
          v-model="queryParams.commissionStatus"
          placeholder="Select Commission Status"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in payStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.invoice.customer')" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          :placeholder="t('common.inputText') + t('su.invoice.customer')"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.id"
            :label="customer.name"
            :value="customer.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('su.invoice.brand')" prop="brandId">
        <el-select
          v-model="queryParams.brandId"
          :placeholder="t('common.inputText') + t('su.invoice.brand')"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="brand in brandList"
            :key="brand.id"
            :label="brand.name"
            :value="brand.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('action.search') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('action.reset') }}</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['su:proforma-invoice:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.create') }}
        </el-button>
        <!--        <el-button-->
        <!--          type="success"-->
        <!--          plain-->
        <!--          @click="handleExport"-->
        <!--          :loading="exportLoading"-->
        <!--          v-hasPermi="['su:proforma-invoice:export']"-->
        <!--        >-->
        <!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
        <!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" @sort-change="handleSortChange" :row-class-name="tableRowClassName">
      <!--      <el-table-column label=" 编号" align="center" prop="id" />-->
      <el-table-column label="Invoice" align="center" prop="no" fixed="left" width="120px" sortable="custom">
        <template #default="scope">
          <router-link :to="'/su/ci/view/' + scope.row.id">
            <el-button link type="success">{{ scope.row.no }}</el-button>
          </router-link>
        </template>
      </el-table-column>
<!--      <el-table-column :label="t('su.invoice.status')" align="center" prop="status" fixed="left" width="80px"/>-->
      <el-table-column
        :label="t('su.invoice.invoiceDate')"
        align="center"
        prop="invoiceDate"
        :formatter="dateFormatter2"
        width="140px"
        fixed="left"
        sortable="custom"
      />
      <el-table-column :label="t('su.invoice.customer')" align="center" prop="customerId" width="120px">
        <template #default="scope">
          <SelectTag pro-key="id" pro-name="name" :list-value="customerList" :value="scope.row.customerId" />
        </template>
      </el-table-column>
      <el-table-column label="Profit$" align="center" prop="totalProfitUs" width="120px">
        <template #default="scope">
          {{ priceFmt(scope.row.totalProfitUs) }}
        </template>
      </el-table-column>
      <el-table-column label="Sale$" align="center" prop="totalSaleUs" width="120px">
        <template #default="scope">
          {{ priceFmt(scope.row.totalSaleUs) }}
        </template>
      </el-table-column>
      <el-table-column label="Purhase$" align="center" prop="totalPurhaseUs" width="120px">
        <template #default="scope">
          {{ priceFmt(scope.row.totalPurhaseUs) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('su.invoice.dueDate')"
        align="center"
        prop="dueDate"
        :formatter="dateFormatter2"
        width="120px"
      />
      <el-table-column :label="t('su.invoice.kind')" align="center" prop="kind" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SU_INVOICE_KIND" :value="scope.row.kind" />
        </template>
      </el-table-column>
      <el-table-column :label="t('su.invoice.brand')" align="center" prop="brandId" width="120px">
        <template #default="scope">
          <SelectTag pro-key="id" pro-name="name" :list-value="brandList" :value="scope.row.brandId" />
        </template>
      </el-table-column>
<!--      <el-table-column :label="t('su.invoice.buyer')" align="center" prop="buyer" />-->
      <el-table-column :label="t('su.invoice.po')" align="center" prop="po" />
      <el-table-column :label="t('su.invoice.payAction')" align="center" prop="payAction" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SU_INVOICD_PAY_ACTION" :value="scope.row.payAction" />
        </template>
      </el-table-column>
      <el-table-column label="Pay" align="center" prop="payStatus" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SU_INVOICE_TERM" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column label="Saler" align="center" prop="term" />
      <el-table-column label="Commission" align="center" prop="commissionStatus" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SU_INVOICE_TERM" :value="scope.row.commissionStatus" />
        </template>
      </el-table-column>
      <el-table-column :label="t('su.invoice.bill')" align="center" prop="bill" />
<!--      <el-table-column :label="t('su.invoice.remarks')" align="center" prop="remarks" />-->
<!--      <el-table-column :label="t('su.invoice.count')" align="center" prop="count">-->
<!--        <template #default="scope">-->
<!--          {{ priceFmt(scope.row.count) }}-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="Operation" align="center" min-width="150px" fixed="right">
        <template #default="scope">
<!--          <router-link :to="'/su/ci/view/' + scope.row.id">-->
<!--            <el-button link type="success">{{ t('action.preview') }}</el-button>-->
<!--          </router-link>-->
<!--          <br/>-->
          <el-button link type="primary" @click="handleConfirm(scope.row.id)" v-hasPermi="['su:commercial-invoice:delete']">Cancel</el-button>
          <el-button link type="primary" @click="refreshPdf(scope.row.id)" v-hasPermi="['su:proforma-invoice:update']">Pdf</el-button>
          <el-button link type="primary" @click="editCi(scope.row)" v-hasPermi="['su:proforma-invoice:update']">Edit</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <el-dialog v-model="editAble" title="Edit CI" :before-close="getList">
    <el-form :model="updateCIInfo" label-position="right" label-width="150px">
      <el-form-item label="CI" prop="ci">
        {{updateCIInfo.no}}
      </el-form-item>

      <el-form-item label="Due Date" prop="dueDate">
        <el-date-picker
          v-model="updateCIInfo.dueDate"
          type="date"
          value-format="x"
          :placeholder="t('common.inputText') + t('su.invoice.dueDate')"
        />
      </el-form-item>

      <el-form-item label="Customer Pay" prop="payStatus">
        <el-select v-model="updateCIInfo.payStatus" placeholder="Select Customer Pay Status">
          <el-option
            v-for="dict in payStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="Saler" prop="saler">
        <el-input v-model="updateCIInfo.term" placeholder="Input Saler" />
      </el-form-item>

      <el-form-item label="Commission Pay" prop="payStatus">
        <el-select v-model="updateCIInfo.commissionStatus" placeholder="Select Customer Pay Status">
          <el-option
            v-for="dict in payStatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editAble = false">Cancel</el-button>
        <el-button type="primary" @click="updateCiInfo">
          Confirm
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import {dateFormatter, dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import { CommercialInvoiceApi, CommercialInvoiceVO } from '@/api/su/ci'
import {CommonApi} from "@/api/su/common";
import { priceFmt } from '@/utils/ft'

/** 形式发票 列表 */
defineOptions({ name: 'CommercialInvoice' })

const payStatus = reactive(
  [
    {
      label:'Pay',
      value: 1,
    },
    {
      label:'Not Pay',
      value: 0,
    }
  ]
)

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<CommercialInvoiceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  invoiceDate: [],
  dueDate: [],
  kind: undefined,
  customerId: undefined,
  brandId: undefined,
  createTime: [],
  prop: undefined,
  order: undefined,
  payStatus: undefined,
  term: undefined,
  commissionStatus: undefined,
})

const tableRowClassName = ({
                             row,
                             rowIndex,
                           }) => {

  return row.payStatus === 0 ? 'warning-row' : 'success-row'
}

const updateCIInfo = ref({
  id: undefined,
  no: undefined,
  invoiceDate: undefined,
  dueDate: undefined,
  kind: undefined,
  customerId: undefined,
  brandId: undefined,
  companyId: undefined,
  companyBankId: undefined,
  supplierId: undefined,
  supplierBankId: undefined,
  buyer: undefined,
  supplerManager: undefined,
  shipTo: undefined,
  po: undefined,
  notes: undefined,
  payAction: undefined,
  term: undefined,
  bill: undefined,
  remarks: undefined,
  count: undefined,
  exchange: undefined,
  tax: undefined,
  productSaleUs: undefined,
  productSaleRmb: undefined,
  productPurhaseUs: undefined,
  productPurhaseRmb: undefined,
  otherSaleUs: undefined,
  otherSaleRmb: undefined,
  otherPurhaseUs: undefined,
  otherPurhaseRmb: undefined,
  discountSaleUs: undefined,
  discountSaleRmb: undefined,
  discountPurhaseUs: undefined,
  discountPurhaseRmb: undefined,
  totalSaleUs: undefined,
  totalSaleRmb: undefined,
  totalPurhaseUs: undefined,
  totalPurhaseRmb: undefined,
  productItems: undefined,
  otherItems: undefined,
  payStatus: undefined,
  commissionStatus: undefined,
})

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const editAble = ref(false)
const editCi = async(row) => {
  updateCIInfo.value = row
  editAble.value = true
}

const updateCiInfo = async () => {
  await CommercialInvoiceApi.updateCommercialInvoiceStatus(updateCIInfo.value);
  editAble.value = false
  getList()
}

const brandList = ref([])
const getBrandList = async () => {
  brandList.value = await CommonApi.getBrandList()
}

const customerList = ref([])
const getCompanyList = async () => {
  customerList.value = await CommonApi.getCustomerList()
}


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CommercialInvoiceApi.getCommercialInvoicePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const handleSortChange = async(column) => {
  const { prop, order } = column
  queryParams.prop = prop
  queryParams.order = order
  await getList()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const refreshPdf = async (id: number) => {
  try {
    // 删除的二次确认
    await message.confirm('Confirm refresh pdf?')
    // 发起删除
    await CommercialInvoiceApi.refreshPdf(id)
    // message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const handleConfirm = async (id: number) => {
  try {
    // 删除的二次确认
    await message.confirm('确认该订单后，不可编辑')
    // 发起删除
    await CommercialInvoiceApi.deleteCommercialInvoice(id)
    message.success(t('common.success'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CommercialInvoiceApi.exportCommercialInvoice(queryParams)
    download.excel(data, '形式发票.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getBrandList()
  getCompanyList()
  getList()
})
</script>

<style>
.el-table__body tr:hover > td {
  background-color: var(--el-table-tr-hover-bg-color) !important;
}

.el-table .warning-row {
  background-color: var(--el-color-warning) !important;
}

.el-table .success-row {
  background-color: var(--el-color-success-light-9) !important;
}
</style>
